package org.zerta.troops.core;
import org.zerta.troops.network.TroopsNetworkServer;
import org.zerta.troops.server.ServerConsole;
import org.zerta.troops.common.Game;
import org.zerta.troops.common.GameState;
import org.zerta.troops.common.Turn;


public class TroopsServerBookkeeper implements Runnable {
	
	public static final int LOCK_TIME_OUT = 10;
	private TroopsNetworkServer troopsNetworkServer;
	private Game game;
	private ServerConsole console;
	
	public TroopsServerBookkeeper( TroopsNetworkServer troopsNetworkServer, ServerConsole console ) {
		this.troopsNetworkServer = troopsNetworkServer;
		game = troopsNetworkServer.getGame();
	}

	@Override
	public void run() {
		Object lock = troopsNetworkServer.getLock();
		synchronized(lock) {
			while ( true ) {
				if (game.isStarted()) {
					if ( ! game.allPlayersSubmittedCurrentTurn()) {
						try {
							lock.wait(LOCK_TIME_OUT);
							continue;
						} catch (InterruptedException e) {
							e.printStackTrace();
							continue;
						}
					} else {
						TurnProcessor turnProcessor = new TurnProcessor();
						Turn turn = game.getCurrentTurn();
						game.advanceTurn();
						GameState gameState = turnProcessor.processTurn(turn, console);
						turn.setGameState(gameState);
						game.setLastProcessedTurn(turn);
					}
				}
			}
		}
	}

}
